<template>
  <!-- 搜索栏 -->
  <QueryModal 
    :queryText="queryText" 
    :queryState="queryState"
    :options="options"
    @change="tagAll"
    @reset="reset"
    @search="search"
    type="type"
  />

  <!-- 表头 -->
  <MainTitleModal 
    style="margin-bottom: 20px;"
    :selectkeys="selectkeys" 
    @exportExcel="exportExcel"
  />

  <!-- 选项 -->
  <a-space style="display: flex; justify-content: space-between; margin-bottom: 10px;">
    <a-button type="primary" @click="edit('add')">新增</a-button>
    <a-button @click="del(selectkeys)" :disabled="selectkeys.length === 0" type="primary" danger>删除选中项</a-button>
  </a-space>

  <!-- 调查报告表 -->
  <TableModal 
    :loading="loading"
    :columns="columns"
    :data="dataList"
    :total="total"
    :pagination="paginationParams"
    v-model:page="paginationParams.pageIndex"
    v-model:idx="selectkeys"
    @edit="edit"
    @del="del"
  >
    <template #bodyCell="{column, record}">
      <template v-if="column.dataIndex === 'surveyInsect'">
        <a-tag v-for="(item, index) in record.surveyInsect" :key="index" color="green">{{ item }}</a-tag>
      </template>
    </template>
  </TableModal>

  <!-- 弹出抽屉 -->
  <DreweModal
    v-model:open="open"
    :editType="editType"
    @close="open = false"
  >
    <template #bodycontent>
      <a-form 
        :model="detailInfo"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item label="田地类型">
          <a-select v-model:value="detailInfo.fieldType">
            <a-select-option v-for="item in fieldOptions" :key="item.label" :value="item.label">{{ item.label }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="调查人">
          <a-input v-model:value="detailInfo.surveyer"/>
        </a-form-item>
        <a-form-item label="调查病虫害">
          <a-input v-model="detailInfo.surveyInsect" style="cursor: pointer;" disabled>
            <template #addonAfter>
              <EllipsisOutlined @click="visible = true"/>
            </template>
            <template #prefix>
              <a-tag @close="tagClose" v-for="(item,index) in detailInfo.surveyInsect" :key="index" color="green" closable>{{ item }}</a-tag>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item label="图片内容">
          <UpLoadModal v-model:img="detailInfo.url"></UpLoadModal>
        </a-form-item>
        <a-form-item label="调查时间">
          <a-range-picker v-model:value="detailInfo.surveyDate" />
        </a-form-item>
        <a-space style="display: flex; justify-content: center;">
          <a-button @click="open = false" type="primary">取消</a-button>
          <a-button @click="save" type="primary">保存</a-button>
        </a-space>
      </a-form>
    </template>
  </DreweModal>

  <!-- 弹框 -->
  <PopupModal
    v-model:open="visible"
    v-model:keys="selKeys"
    @cancel="visible = false"
  />
</template>
<script setup>
import { ref, onMounted, watch } from 'vue'
import QueryModal from '@/component/QueryModal.vue'
import MainTitleModal from '@/component/MainTitleModal.vue'
import TableModal from '@/component/TableModal.vue'
import DreweModal from '@/component/DrawerModal.vue'
import UpLoadModal from '@/component/UploadModal.vue'
import PopupModal from '@/component/PopupModal.vue'
import Api from '@/api/survey'
import dayjs from 'dayjs'
import { message, Modal } from 'ant-design-vue'
import { EllipsisOutlined } from '@ant-design/icons-vue' 

// 公共配置项
const fieldOptions = [
  {
    label: '系统田1'
  },
  {
    label: '系统田2'
  },
  {
    label: '系统田3'
  },
]

// 查询组件
const queryText = ref('查询条件')
const queryState = ref({
  // surveyDate: 'today',
  // surveyTime: [],
  // surveyType: '',
  // surveyer: '',
  // fieldType: '',
  // checkedList: []
})
const options = [
  {
    label: '稻纵卷叶螟',
    value: '稻纵卷叶螟',
  },
  {
    label: '稻飞虱',
    value: '稻飞虱',
  },
  {
    label: '稻纹枯病',
    value: '稻纹枯病',
  },
  {
    label: '小麦赤霉病',
    value: '小麦赤霉病',
  },
  {
    label: '小麦条锈病',
    value: '小麦条锈病',
  },
  {
    label: '小麦蚜虫',
    value: '小麦蚜虫',
  }
]

// Table组件
const loading = ref(false)
const dataList = ref([])
const total = ref(0)
const selectkeys = ref([])
const paginationParams = ref({
  pageIndex: 1,
  pageSize: 5,
})

// 抽屉组件
const open = ref(false)
const editType = ref('')
const idEdit = ref(0)
const tags = ref([])
const facilityId = ref(0)
const detailInfo = ref({
  fieldType: '',
  surveyer: '',
  surveyInsect: [],
  url: '',
  surveyDate: []
})

// 弹框组件
const visible = ref(false)
const selKeys = ref([])

// function
const getSurveyList = async (data) => {
  loading.value = true
  const res = await Api.getSurveyRecordList({...paginationParams.value, ...data})
  dataList.value = res.data
  total.value = res.total
  dataList.value.forEach(item => {
    item.key = item._id
  })
  loading.value = false
  selectkeys.value = []
}

// 重置
const reset = () => {
  queryState.value = {}
  paginationParams.pageIndex = 1
  getSurveyList()
}

// 搜索
const search = () => {
  if (queryState.value.surveyTime) {
    queryState.value.surveyStart = dayjs(queryState.value.surveyTime[0]).format('YYYY/MM/DD hh:mm:ss')
    queryState.value.surveyEnd = dayjs(queryState.value.surveyTime[1]).format('YYYY/MM/DD hh:mm:ss')
  }
  delete queryState.value.surveyTime
  paginationParams.pageIndex = 1
  getSurveyList(queryState.value)
}

const tagAll = (data) => {
  queryState.value.surveyInsect = data
}

// 导出
const exportExcel = () => {
  
}

// 编辑
const edit = (type, id) => {
  open.value = true
  editType.value = type
  if (type === 'edit') {
    const res = dataList.value.find(item => item._id === id)
    if (res.surveyStart && res.surveyEnd) {
      res.surveyDate = [dayjs(res.surveyStart),dayjs(res.surveyEnd)]
    }
    detailInfo.value = res
    facilityId.value = res._id
    idEdit.value = 1
  } 
}

// 保存
const save = async () => {
  if (detailInfo.value.surveyDate) {
    detailInfo.value.surveyStart = dayjs(detailInfo.value.surveyDate[0]).format('YYYY/MM/DD hh:mm:ss')
    detailInfo.value.surveyEnd = dayjs(detailInfo.value.surveyDate[1]).format('YYYY/MM/DD hh:mm:ss')
  }
  const result = await Api.operaSurveyRecord({
    idEdit: idEdit.value,
    facilityId: facilityId.value,
    ...detailInfo.value
  })
  if (result.code !== 100) return message.error(result.message)
  message.success(result.message)
  open.value = false
}

// 删除
const del =(id) => {
  id = typeof id === 'string' ? [id] : id
  Modal.confirm({
    title: '您确定要删除吗',
    onOk: async () => {
      const res = await Api.deleteSurveyRecord({_id: id})
      if (res.code !== 100) return message.error(res.message) 
      message.success(res.message)
      paginationParams.value.pageIndex = 1
      getSurveyList()
    }
  })
}


const tagClose = (e) => {
  
}

// 格式化日期
const getsurDate = (record) => {
  return `${dayjs(record.surveyStart).format('YYYY-MM-DD hh:mm:ss')} - ${dayjs(record.surveyEnd).format('YYYY-MM-DD hh:mm:ss')}`
}

const getImgLength = (text) => {
  return 1
}


const columns = [
  {title: '序号', dataIndex: 'index', align: 'center'},
  {title: '调查时间', dataIndex: 'surveyDate', align: 'center', customRender: ({ record }) => getsurDate(record)},
  {title: '田块类型', dataIndex: 'fieldType', align: 'center'},
  {title: '调查人', dataIndex: 'surveyer', align: 'center'},
  {title: '图片数量', dataIndex: 'url', align: 'center', customRender: ({ text }) => getImgLength(text)},
  {title: '调查病虫害', dataIndex: 'surveyInsect', align: 'center'},
  {title: '操作', dataIndex: 'opera', align: 'center'},
];

onMounted(() => {
  getSurveyList()
})

watch([paginationParams, open], () => {
  getSurveyList()

  if (open.value === false) {
    detailInfo.value = {}
  }
}, {
  deep: true
})

</script>

<style lang="scss" scoped>
.ant-input {
  :where(.css-dev-only-do-not-override-3m4nqy).ant-input-disabled, 
  :where(.css-dev-only-do-not-override-3m4nqy).ant-input[disabled] {
    cursor: pointer;
  }
}
</style>